import re
import  hanlp
import  math,time
from Tables import XXJL,ZWJL


class dofx:
    def __init__(self) :
        self.nowstance = None
        self.HanLP=None
        self.xxjl = [] #学习经历
        self.zwjl = [] #职务经历
        self.jdjl = [] #借调经历
        self.txt = ''  #中间存的文本
        self.bigTree = None #最大树
        self.zyxx = [] #学习院校暂存
        self.fs = {'dc':{},'pd':[]}  #强制分词
 
        self.session = None

        self.sfz = None  #身份证
        self.name = None #姓名
        self.pid = None  #系统id  
        self.cssj = '' #出生时间

    def qgjz(self,id,name,dl,cssj,sfz,session):

        self.sfz = sfz
        self.name = name
        self.pid = id
        self.cssj = cssj

        self.session = session

        self.loadDM()
        self.HanLP: MultiTaskLearning = hanlp.load(hanlp.pretrained.mtl.CLOSE_TOK_POS_NER_SRL_DEP_SDP_CON_ELECTRA_SMALL_ZH)
        tok: TaggingTokenization = self.HanLP['tok/fine']
        tok.dict_force = None
        tok.dict_combine = self.fs['dc']
        jzs=dl.split("\r\n")
        self.xxjl = []
        self.jdjl= []
        try:
          for jz in jzs:
            self.txt=''
            self.tranData(jz)
          self.session.commit()
        except Exception as e:
          with open('error.txt','a+',encoding='utf-8') as f:
            f.write(("姓名"+self.name+"，错误："+str(e)))
  
  
    def tranData(self,jz):
        #1.处理中英文符号
        jz = jz.replace("(","（").replace(")","）").replace("-","-").replace(" ","")   
        sjs = re.findall("\d{4}\.\d{2}",jz)
        if '在家'  in jz or '待业' in  jz:
          print(sjs[0],sjs[1],'在家待业')
        else:  
          if len(sjs) == 2:
              if '学生'  in  jz  or '学习'  in jz or '就读'  in jz:
                  xxjl=self.dofxxx(jz)
                  x1 =XXJL(kssj=xxjl[0],jssj=xxjl[1],sjcd=xxjl[2],ksnl=xxjl[3],jsnl=xxjl[4],xx=xxjl[5],zy=xxjl[6],pid=self.pid,sfz=self.sfz,name=self.name) 
                  self.session.add(x1)
              else:
                  dd = jz.split(" ")[-1]
                  zwjl=self.dofxzw(dd)
                  z1 = ZWJL(kssj=zwjl[0],jssj=zwjl[1],sjcd=zwjl[2],ksnl=zwjl[3],jsnl=zwjl[4],dm=zwjl[5],gzdw=zwjl[6],gzzw=zwjl[7],gzlx=zwjl[8],pid=self.pid,sfz=self.sfz,name=self.name) 
                  self.session.add(z1)
          elif len(sjs)  == 4:
              dd,jl = self.getxx(jz)
              if '学生'  in  jl  or '学习'  in jl or '就读'  in jl:
                  xxjl=self.dofxxx(jl)
                  x2 = XXJL(kssj=xxjl[0],jssj=xxjl[1],sjcd=xxjl[2],ksnl=xxjl[3],jsnl=xxjl[4],xx=xxjl[5],zy=xxjl[6],pid=self.pid,sfz=self.sfz,name=self.name)
                  self.session.add(x2)
              else:
                  zwjl= self.dofxzw(jl)
                  z2=ZWJL(kssj=zwjl[0],jssj=zwjl[1],sjcd=zwjl[2],ksnl=zwjl[3],jsnl=zwjl[4],dm=zwjl[5],gzdw=zwjl[6],gzzw=zwjl[7],gzlx=zwjl[8],pid=self.pid,sfz=self.sfz,name=self.name) 
                  self.session.add(z2)
          elif len(sjs) == 1:
              self.zwjl.append(self.dofxzw(jz))

    #分析职务
    def dofxzw(self,s):
      zwtype = '地方'
      m =  re.search('服役|副连|正连|连长|副排|正排|排长|副营|正营|营长|副团|正团|团长|副师|正师|师长|团军|部队|武装部',s)
      if m is not None:
        zwtype = m.group(0)
      sjs = re.findall("\d{4}\.\d{2}",s)
      if len(sjs) >1:        
        ls = [i.end() for i in re.finditer(sjs[1], s)]  
        wb = s[ls[0]:]
        jssj = sjs[1]
      else:
        wb = s.split("-")[-1]
        jssj = time.strftime("%Y.%m", time.localtime())      
      doc = self.HanLP(wb, tasks=['pos', 'con'])
      docn = doc['con']

      fg = 0
      dm = []
      qt = []
      dw = ''
      islx = True
      for i,k in enumerate(doc['pos/ctb']):
        if doc['tok/fine'][i] in self.fs['pd'] and islx: 
          dw = doc['tok/fine'][i]
          dm.append(doc['tok/fine'][i])
        elif k == 'NR' and islx:
          dm.append(doc['tok/fine'][i])
        else:
          islx = False
          qt.append(doc['tok/fine'][i])
      dm = ''.join(dm)
      qt = ''.join(qt)
      doc = self.HanLP(qt, tasks=['pos', 'con'])
      docn = doc['con']
      if '乡' in wb or '镇'  in wb or '街道'  in wb:
        self.gety(docn)
        zw = self.txt
      else:   
        dw,zw = self.fgxx(docn)     
      return [sjs[0],jssj,self.calYear(sjs[0],jssj,2),self.calYear(sjs[0],self.cssj,0),self.calYear(jssj,self.cssj,0),dm,dw,zw,zwtype]

    #分析学习
    def dofxxx(self,s):
      Haszy = True
      if '中学' in s or '高中' in s:
        Haszy = False    
      s=s.split("专业")[0]+'专业'
      sjs = re.findall("\d{4}\.\d{2}",s)        
      ls = [i.end() for i in re.finditer(sjs[1], s)]  
      wb = s[ls[0]:]      
      wb = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])","",wb)
      self.zyxx = []
      doc = self.HanLP(wb.replace("学习","").replace("在","").replace("于","").replace("就读",""), tasks=['pos', 'con'])
      docn = doc['con']
      # print(doc.pretty_print())
      self.getbigTree(docn)
      for i in self.bigTree:
        self.txt = ''
        self.gety(i)
        self.zyxx.append(self.txt)
        #学习经历开始时间，学习经历结束时间，学习时长，学习开始年龄，学习结束年龄，学校，专业
      zy =''
      if Haszy:
        zy = self.zyxx[1]
      else:
        zy = ''
      return [sjs[0],sjs[1],self.calYear(sjs[0],sjs[1],2),self.calYear(sjs[0],self.cssj,0),self.calYear(sjs[1],self.cssj,0),self.zyxx[0],zy]

    #计算年龄差值
    def  calYear(self,d1,d2,ws):
      if '.'  not in d1:
        d1=d1[0:4]+'.'+d1[5:6]
      if '.'  not in d2:
        d2=d2[0:4]+'.'+d2[5:6]
      return round(abs(float(d1)-float(d2)),ws)

    #获取子树叶子结点文本
    def  gety(self,ar):
      if len(ar) != 1  or  'Tree' in str(ar[-1].__class__):
        for i in ar:
          self.gety(i)
      else:
        self.txt = self.txt+ar[-1]

    #获取最大分支子树
    def getbigTree(self,ar):
      if len(ar) == 1:
        self.getbigTree(ar[0])
      else:
        self.bigTree = ar
        # self.bigTree = None
        # height = 0
        # for i in ar:
        #   if i.height() > height:
        #     self.bigTree = i
        #     height = i.height()

    #匹配拆分出简历及学习经历
    def getxx(self,s):
        ls = [{"k":i.start(),"t":"l"} for i in re.finditer('（', s)]
        rs = [{"k":i.start(),"t":"r"} for i in re.finditer('）', s)] 
        ls.extend(rs) 
        ls = sorted(ls,key = lambda e:e.__getitem__('k'),reverse = True)
        zzs = ls 
        sz = []
        ls=[0,0]
        for index,zz in enumerate(zzs):
            if len(sz) == 1 :
                if zz['t'] == 'l':
                    ls[0] = zz['k']
                    ls[1] = sz[0]['k']
                    break
                else:
                    sz.append(zz)
            elif len(sz) > 1:
                if zz['t'] == 'l':
                    sz.pop()
                else:
                    sz.append(zz)
            else:
                sz.append(zz)  
        return s[0:ls[0]].split(" ")[-1],s[ls[0]+1:ls[1]]

    #拆分单位，职务
    def fgxx(self,s):
      isS = False
      dw = ''
      zw = ''
      for i in s[0]:
        if self.txt != '' and isS == False:
          dw = self.txt
          self.txt = ''
          isS = True
        self.gety(i)
      zw = self.txt
      return dw,zw

    #载入地名
    def loadDM(self):
      with open('dm.txt','r',encoding='utf-8') as f:
        dms = f.read().splitlines()
        self.fs['dc']=set(dms)
        self.fs['pd']=dms
